package net.zdsoft.wpchat.android.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.zdsoft.keel.util.Validators;

/**
 * 提供访问HTTP服务的工具类
 * 
 * @author xuan
 * @version $Revision: 1.0 $, $Date: 2013-3-25 上午9:24:40 $
 */
public abstract class HttpUtils {
    private static Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * POST请求
     * 
     * @param url
     * @param paramsMap
     * @param md5Key
     * @return
     */
    public static String post(String url, Map<String, String> paramsMap) {
        if (Validators.isEmpty(url)) {
            return null;
        }

        if (null == paramsMap) {
            paramsMap = new HashMap<String, String>();
        }

        // if (paramsMap.toString().length() < 300) {
        // 如果带有图片的话不输出图片的内容
        // log.debug("POST请求地址：" + url + paramsMap.toString());
        // }

        String result = "";
        try {
            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url) {
                @Override
                public String getRequestCharSet() {
                    return "UTF-8";// 参数UTF-8编码
                }
            };

            // 添加参数
            for (Entry<String, String> entry : paramsMap.entrySet()) {
                postMethod.addParameter(new NameValuePair(entry.getKey(), entry.getValue()));
            }
            client.executeMethod(postMethod);
            result = postMethod.getResponseBodyAsString();
        }
        catch (Exception e) {
            log.error("HttpUtils请求异常错误，原因：" + e);
        }

        return result;
    }

    public static void main(String[] args) {
        System.out.println(post("http://blog.xuanner.com/apk-count/show.php", null));
    }

}
